using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Linq.Expressions;

namespace Magiq.Sql {
  public class QueryColumnAssignmentBuilder {
    private readonly DataContext dataContext;
    private readonly IList<object> parameters;

    public QueryColumnAssignmentBuilder(DataContext dataContext) {
      ColumnAssignments = new Dictionary<string, string>();
      this.dataContext = dataContext;
      parameters = new List<object>();
    }

    public object[] QueryParameters {
      get { return parameters.ToArray(); }
    }

    private IDictionary<string, string> ColumnAssignments { get; set; }

    public IEnumerable<string> Columns {
      get { return ColumnAssignments.Keys; }
    }

    public IEnumerable<string> Values {
      get { return ColumnAssignments.Values; }
    }

    public void AddColumnValue(string column, string sqlValue) {
      ColumnAssignments.Add(column, sqlValue);
    }

    public string ValueFor(string column) {
      return ColumnAssignments[column];
    }

    public string AddParameter<R>(R value) {
      var metaType = dataContext.Mapping.GetMetaType(typeof (R));

      if (metaType.IsEntity)
        throw new InvalidOperationException("Value can't be an entity");

      if (Equals(value, null))
        return "null";

      parameters.Add(value);

      return "@p" + (parameters.Count - 1);
    }

    public string AddParameters<T, R>(Expression<Func<T, R>> expression) {
      throw new NotImplementedException();
    }
  }
}